package xlog

import (
	"bytes"
	"context"
	"log/slog"
)

type Logger struct {
	logger *slog.Logger
	config *Config
}

func NewLogger(config *Config) (*Logger, error) {
	if config == nil {
		config = DefaultConfig()
	}
	config.check()

	handler, err := NewMultiHandler(config)
	if err != nil {
		return nil, err
	}
	logger := slog.New(handler)
	return &Logger{logger: logger, config: config}, nil
}

func (l *Logger) Logger() *slog.Logger {
	return l.logger
}

// Write 写入，用于log.New() log.Logger的实现
func (l *Logger) Write(p []byte) (int, error) {
	p = bytes.TrimSpace(p)
	l.logger.LogAttrs(context.Background(), slog.LevelInfo, string(p))
	return len(p), nil
}
